package com.free.semantic.web.controller;

import com.free.semantic.core.service.UserService;
import com.free.semantic.model.conceptmodel.User;
import com.free.semantic.web.common.ApiResponse;
import com.free.semantic.web.security.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class UserAuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    public ApiResponse<Map<String, Object>> login(@RequestParam String username, @RequestParam String password) {
        User user = userService.login(username, password);
        if (user == null) {
            return ApiResponse.error("用户名或密码错误");
        }

        String token = jwtUtil.generateToken(user.getId());
        Map<String, Object> response = new HashMap<>();
        response.put("user", user);
        response.put("token", token);

        return ApiResponse.success(response);
    }

    @PostMapping("/register")
    public ApiResponse<User> register(@RequestParam String username, @RequestParam String password) {
        // 检查用户名是否存在
        if (userService.checkUsernameExists(username)) {
            return ApiResponse.error("用户名已存在");
        }
        User user = userService.register(username, password);
        if (user == null) {
            return ApiResponse.error("注册失败");
        }
        return ApiResponse.success(user);
    }

    @PostMapping("/password")
    public ApiResponse<Boolean> updatePassword(
            @RequestParam Long userId,
            @RequestParam String oldPassword,
            @RequestParam String newPassword) {

        // 检查新密码强度
        if (!userService.validatePasswordStrength(newPassword)) {
            return ApiResponse.error("新密码强度不符合要求");
        }

        boolean success = userService.updatePassword(userId, oldPassword, newPassword);
        if (!success) {
            return ApiResponse.error("密码更新失败，请检查旧密码是否正确");
        }
        return ApiResponse.success(true);
    }
} 